package com.immortal.module.security.handler;

import com.immortal.core.module.integration.IntegrationAuthentication;
import com.immortal.core.module.integration.IntegrationAuthenticationContext;
import com.immortal.core.module.integration.IntegrationAuthenticationFilter;
import com.immortal.core.module.integration.authenticator.IntegrationAuthenticator;
import com.immortal.core.module.res.ApiResult;
import com.immortal.core.utils.http.ServletUtils;
import com.immortal.module.security.ImAuthenticationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

@Slf4j
public class AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    public AuthenticationFailureHandler() {
    }

    public AuthenticationFailureHandler(String defaultFailureUrl) {
        super(defaultFailureUrl);
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        if (!complete(request, response, e)) {
            if (ServletUtils.isAjaxRequest(request)) {
                ServletUtils.renderResult(response, ApiResult.Custom().failure(e.getMessage()).path(request.getRequestURI()));
            } else {
                super.onAuthenticationFailure(request, response, e);
            }
        }
    }

    /**
     * 进行预处理
     *
     * @param auth
     */
    private boolean complete(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        IntegrationAuthentication integrationAuthentication = IntegrationAuthenticationContext.get();
        if (integrationAuthentication == null) {
            integrationAuthentication = new IntegrationAuthentication();
        }
        Collection<IntegrationAuthenticator> authenticators = ImAuthenticationFilter.authenticators;
        if(authenticators!=null){
            for (IntegrationAuthenticator authenticator : authenticators) {
                if (authenticator.support(integrationAuthentication)) {
                    return authenticator.complete(request, response, null, e);
                }
            }
        }
        return false;
    }
}